tx <- readRDS("temp/tx_submitters.rds")
tx$income <- tx$income / 1000


lapply(c("primary", "ex-all", "include-all", "birdie"), function(r){
  
  if(r == "primary" | r == "birdie"){
    tx <- filter(tx, !bad_counties2)
  }else if(r == "ex-all"){
    tx <- filter(tx, !bad_counties)
  }
  
  if(r == "birdie"){
    tx <- tx |> 
      mutate(pred.whi = pr_white,
             pred.bla = pr_black,
             pred.his = pr_hisp,
             pred.asi = pr_asian,
             pred.oth = pr_other,
             pred.nw = 1 - pred.whi)
  }
  
  tx <- tx |> 
    mutate(pp = (BallotType_Primary_2018_03_06 != "") +
             (BallotType_Primary_2010_03_02 != "") +
             (BallotType_Primary_2014_03_04 != ""),
           app_rej_nonsb1 = app_rejected_any - app_rejected_sb1,
           ballot_rej_nonsb1 = ballot_rejected_any - ballot_rejected_sb1,
           male = Voters_Gender == "M")
  
  m1 <- feols(app_rejected_sb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                Voters_Age + male + party + pp | Voters_FIPS, tx)
  
  m2 <- feols(app_rej_nonsb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                Voters_Age + male + party + pp | Voters_FIPS, tx)
  
  m3 <- feols(ballot_rejected_sb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                Voters_Age + male + party + pp | Voters_FIPS, filter(tx, ballot_submitted))
  
  m4 <- feols(ballot_rej_nonsb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                Voters_Age + male + party + pp | Voters_FIPS, filter(tx, ballot_submitted))
  
  rows <- tribble(~term,          ~m1,  ~m2, ~m3, ~m4,
                  "County Fixed Effects", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$")
  
  attr(rows, 'position') <- c(17:17)
  
  modelsummary(list("SB1" = m1, "Non-SB1" = m2, "SB1" = m3, "Non-SB1" = m4),
               statistic = "std.error",
               stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001),
               coef_map = c("pred.bla" = "P(Black)",
                            "pred.his" = "P(Latino)",
                            "pred.asi" = "P(Asian)",
                            "pred.oth" = "P(Other Race)",
                            "Voters_Age" = "Age",
                            "maleTRUE" = "Male",
                            "party" = "Partisan Score",
                            "pp" = "Past Primary Turnout",
                            "(Intercept)" = "Intercept"),
               add_rows = rows,
               notes = list("``P(White)'' is reference category for race.",
                            "Partisan score determined by partisan primary participation,",
                            "2010--2020. It ranges from -1 (most Democratic) to 1 (most Republican).",
                            "Past primary turnout is the number of midterm primaries",
                            "a voter participated in between 2010 and 2018.",
                            "Standard errors clustered by county."),
               gof_omit = 'DF|Deviance|AIC|BIC|Within|Pseudo|Log|Std|FE|RMSE',
               title = paste0("\\label{tab:rej-reg-", r, "} Rejection Rates, 2022 Primary"),
               output = "latex",
               escape = FALSE) |> 
    add_header_above(c(" " = 1, "Application Rejections" = 2, "Ballot Rejections" = 2)) |>
    # kable_styling(latex_options="scale_down") |> 
    save_kable(paste0(out, "Tables/rej_rate_", r, ".tex"))
  
  if(r == "primary" | r == "birdie"){
    m1 <- feols(app_rejected_sb1 ~ pred.nw +
                  Voters_Age + male + party + pp | Voters_FIPS, tx)
    
    m2 <- feols(app_rej_nonsb1 ~ pred.nw +
                  Voters_Age + male + party + pp | Voters_FIPS, tx)
    
    m3 <- feols(ballot_rejected_sb1 ~ pred.nw +
                  Voters_Age + male + party + pp | Voters_FIPS, filter(tx, ballot_submitted))
    
    m4 <- feols(ballot_rej_nonsb1 ~ pred.nw +
                  Voters_Age + male + party + pp | Voters_FIPS, filter(tx, ballot_submitted))
  
    rows <- tribble(~term,          ~m1,  ~m2, ~m3, ~m4,
                    "County Fixed Effects", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$")
    
    attr(rows, 'position') <- c(9:9)
    
    modelsummary(list("SB1" = m1, "Non-SB1" = m2, "SB1" = m3, "Non-SB1" = m4),
                 statistic = "std.error",
                 stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001),
                 coef_map = c("pred.nw" = "P(Nonwhite)",
                              "Voters_Age" = "Age",
                              "maleTRUE" = "Male",
                              "demTRUE" = "Democrat",
                              "pp" = "Past Primary Turnout",
                              "(Intercept)" = "Intercept"),
                 add_rows = rows,
                 notes = list("``P(White)'' is reference category for race.",
                              "Partisan score determined by partisan primary participation,",
                              "2010--2020. It ranges from -1 (most Democratic) to 1 (most Republican).",
                              "Past primary turnout is the number of midterm primaries",
                              "a voter participated in between 2010 and 2018.",
                              "Standard errors clustered by county."),
                 gof_omit = 'DF|Deviance|AIC|BIC|Within|Pseudo|Log|Std|FE|RMSE',
                 title = paste0("\\label{tab:rej-reg-", r, "} Rejection Rates, 2022 Primary"),
                 output = "latex",
                 escape = FALSE) |> 
      add_header_above(c(" " = 1, "Application Rejections" = 2, "Ballot Rejections" = 2)) |>
      # kable_styling(latex_options="scale_down") |> 
      save_kable(paste0(out, "Tables/rej_rate_", r, "_nw.tex"))
    
    m1 <- feols(app_rejected_sb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                  Voters_Age + male + party + pp + income + education | Voters_FIPS, tx)
    
    m2 <- feols(app_rej_nonsb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                  Voters_Age + male + party + pp + income + education | Voters_FIPS, tx)
    
    m3 <- feols(ballot_rejected_sb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                  Voters_Age + male + party + pp + income + education | Voters_FIPS, filter(tx, ballot_submitted))
    
    m4 <- feols(ballot_rej_nonsb1 ~ pred.bla + pred.his + pred.asi + pred.oth +
                  Voters_Age + male + party + pp + income + education | Voters_FIPS, filter(tx, ballot_submitted))
    
    rows <- tribble(~term,          ~m1,  ~m2, ~m3, ~m4,
                    "County Fixed Effects", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$")
    
    attr(rows, 'position') <- c(31:31)
    
    modelsummary(list("SB1" = m1, "Non-SB1" = m2, "SB1" = m3, "Non-SB1" = m4),
                 statistic = "std.error",
                 stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001),
                 coef_map = c("pred.bla" = "P(Black)",
                              "pred.his" = "P(Latino)",
                              "pred.asi" = "P(Asian)",
                              "pred.oth" = "P(Other Race)",
                              "Voters_Age" = "Age",
                              "maleTRUE" = "Male",
                              "party" = "Partisan Score",
                              "pp" = "Past Primary Turnout",
                              "income" = "Household Income from L2 (000s)",
                              "educationlths" = "Less than HS Degree",
                              "educationhs" = "HS Degree",
                              "educationsome college" = "Some College",
                              "educationvocational" = "Vocational Degree",
                              "educationgrad" = "Graduate Degree",
                              "educationunknown" = "Education Unknown",
                              "(Intercept)" = "Intercept"),
                 add_rows = rows,
                 notes = list("``P(White)'' is reference category for race. ``Bachelor's Degree'' is reference category",
                              " for education. Partisan score determined by partisan primary participation, 2010--2020.",
                              "It ranges from -1 (most Democratic) to 1 (most Republican). Past primary turnout is the",
                              "number of midterm primaries a voter participated in between 2010 and 2018.",
                              "Standard errors clustered by county."),
                 gof_omit = 'DF|Deviance|AIC|BIC|Within|Pseudo|Log|Std|FE|RMSE',
                 title = paste0("\\label{tab:rej-reg-l2-covs-", r, "} Rejection Rates, 2022 Primary"),
                 output = "latex",
                 escape = FALSE) |> 
      add_header_above(c(" " = 1, "Application Rejections" = 2, "Ballot Rejections" = 2)) |>
      # kable_styling(latex_options="scale_down") |> 
      save_kable(paste0(out, "Tables/rej_rate_", r, "_l2_covars.tex"))
    
    
    }
  
  ##################
  
  ll1 <- left_join(
    tx |> 
      summarize(across(starts_with("pred."), ~ sum(., na.rm = T))) |> 
      pivot_longer(cols = starts_with("pred"), names_to = "race", values_to = "submitted", names_prefix = "pred."),
    tx |> 
      filter(app_rejected_sb1) |> 
      summarize(across(starts_with("pred."), ~ sum(., na.rm = T))) |> 
      pivot_longer(cols = starts_with("pred"), names_to = "race", values_to = "rejected", names_prefix = "pred.")
  ) |> 
    mutate(rejection_rate = rejected / submitted,
           race = case_when(race == "whi" ~ "White",
                            race == "bla" ~ "Black",
                            race == "his" ~ "Latino",
                            race == "asi" ~ "Asian",
                            race == "nw" ~ "Nonwhite",
                            T ~ "Other"))
  
  ggplot(filter(ll1, race != "Nonwhite"), aes(x = reorder(race, -rejection_rate), y = rejection_rate)) +
    geom_col(color = "black", fill = "white") +
    theme_bc() +
    scale_y_continuous(labels = percent, limits = c(0, 0.16)) +
    labs(x = "Race", y = "Application\nRejection Rate") +
    geom_text(aes(label = percent(rejection_rate, 0.1)), vjust = -0.3)
  
  ggsave(paste0(out, "Figures/app_rejections_", r, ".png"), width = 4, height = 2, units = "in")
  
  
  ll2 <- left_join(
    tx |> 
      filter(ballot_submitted) |> 
      summarize(across(starts_with("pred."), ~ sum(., na.rm = T))) |> 
      pivot_longer(cols = starts_with("pred"), names_to = "race", values_to = "submitted", names_prefix = "pred."),
    tx |> 
      filter(ballot_rejected_sb1, ballot_submitted) |> 
      summarize(across(starts_with("pred."), ~ sum(., na.rm = T))) |> 
      pivot_longer(cols = starts_with("pred"), names_to = "race", values_to = "rejected", names_prefix = "pred.")
  ) |> 
    mutate(rejection_rate = rejected / submitted,
           race = case_when(race == "whi" ~ "White",
                            race == "bla" ~ "Black",
                            race == "his" ~ "Latino",
                            race == "asi" ~ "Asian",
                            race == "nw" ~ "Nonwhite",
                            T ~ "Other"))
  
  ggplot(filter(ll2, race != "Nonwhite"), aes(x = reorder(race, -rejection_rate), y = rejection_rate)) +
    geom_col(color = "black", fill = "white") +
    theme_bc() +
    scale_y_continuous(labels = percent, limits = c(0, 0.16)) +
    labs(x = "Race", y = "Ballot\nRejection Rate") +
    geom_text(aes(label = percent(rejection_rate, 0.1)), vjust = -0.3)
  
  ggsave(paste0(out, "Figures/ballot_rejections_", r, ".png"), width = 4, height = 2, units = "in")
  
  
  if(r == "primary"){
    ggplot(filter(ll1, race != "Nonwhite"), aes(x = reorder(race, -rejected), y = rejected)) +
      geom_col(color = "black", fill = "white") +
      theme_bc() +
      scale_y_continuous(labels = comma) +
      labs(x = "Race", y = "Applications Rejected") +
      geom_text(aes(label = comma(rejected)), vjust = -0.3)
    
    ggsave(paste0(out, "Figures/app_rejections_", r, "_counts.png"), width = 4, height = 2, units = "in")
    
    
    ggplot(filter(ll2, race != "Nonwhite"), aes(x = reorder(race, -rejected), y = rejected)) +
      geom_col(color = "black", fill = "white") +
      theme_bc() +
      scale_y_continuous(labels = comma) +
      labs(x = "Race", y = "Ballots Rejected") +
      geom_text(aes(label = comma(rejected)), vjust = -0.3)
    
    ggsave(paste0(out, "Figures/ballot_rejections_", r, "_counts.png"), width = 4, height = 2, units = "in")
  }
})

